package de.hub.sar.itsec.sslfetcher.clr;

import java.util.HashMap;
import java.util.Map;

public class ArgReader {
	private static final String ID_ID = "-";
	
	private final Map<String, Argument<?>> args;
	
	public ArgReader() {
		this.args = new HashMap<String, Argument<?>>();
	}
	
	public void add(Argument<?> arg) {
		this.args.put(arg.getId(), arg);
	}
	
	public void scan(final String[] args) {
		Argument<?> arg = null;
		
		for (String s : args) {
			if (s.startsWith(ID_ID) && s.length() > ID_ID.length()) {
				arg = this.args.get(s.substring(ID_ID.length()));
				continue;
			}
			if (arg != null) {
				arg.setValue(s);
				arg = null;
			}
		}
	}
	
	public String checkCompleteness() {
		for (Argument<?> arg : this.args.values()) {
			if (arg.getValue() == null) {
				return arg.getId();
			}
		}
		
		return null;
	}

	public String getHelp(String id) {
		Argument<?> arg;
		
		arg = this.args.get(id);
		if (arg == null) {
			return null;
		}
		
		return arg.getId() + ": " + arg.getHelp();
	}

	public String getHelp() {
		StringBuilder sb;
		
		sb = new StringBuilder();
		sb.append("Command Line Options\n");
		sb.append("--------------------\n");
		
		for (Argument<?> arg : this.args.values()) {
			sb.append('-');
			sb.append(arg.getId());
			sb.append(": ");
			sb.append(arg.getHelp());
			sb.append('\n');
		}
		
		return sb.toString();
	}
	
	public int getIntValue(final String id) {
		Argument<?> arg;
		
		arg = this.args.get(id);
		if (arg == null) {
			return -1;
		}
		
		return (Integer) arg.getValue();
	}
	
	public String getStringValue(final String id) {
		Argument<?> arg;
		
		arg = this.args.get(id);
		if (arg == null) {
			return null;
		}
		
		return (String) arg.getValue();
	}
}
